package com.hrpc.serialize;

import com.hrpc.config.ObjectWrapper;
import com.hrpc.serialize.impl.HessianSerializeImpl;
import com.hrpc.serialize.impl.JDKSerializeImpl;
import com.hrpc.serialize.impl.JSONSerializeImpl;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SerializeFactory {
    private final static Map<String, ObjectWrapper<Serialize>> SERIALIZE_CACHE =new ConcurrentHashMap<>(8);
    private final static Map<Byte,ObjectWrapper<Serialize>> SERIALIZE_CACHE_CODE =new ConcurrentHashMap<>(8);

    static {
        ObjectWrapper<Serialize> jdk = new ObjectWrapper<Serialize>((byte) 1, "jdk", new JDKSerializeImpl());
        ObjectWrapper<Serialize> json = new ObjectWrapper<Serialize>((byte) 2, "json", new JSONSerializeImpl());
        ObjectWrapper<Serialize> hessian = new ObjectWrapper<Serialize>((byte) 3, "hessian", new HessianSerializeImpl());
        SERIALIZE_CACHE.put("jdk",jdk);
        SERIALIZE_CACHE.put("json",json);
        SERIALIZE_CACHE.put("hessian",hessian);
        SERIALIZE_CACHE_CODE.put((byte) 1,jdk);
        SERIALIZE_CACHE_CODE.put((byte) 2,json);
        SERIALIZE_CACHE_CODE.put((byte) 3,hessian);
    }

    /**
     * 使用工厂方法获取一个serializerWrapper
     * @param serializeType
     * @return
     */
    public static ObjectWrapper<Serialize> getSerialize(String serializeType) {
        ObjectWrapper<Serialize> serializeWrapper = SERIALIZE_CACHE.get(serializeType);
        if (serializeWrapper == null){
            return SERIALIZE_CACHE.get("jdk");
        }
        return SERIALIZE_CACHE.get(serializeType);
    }
    public static ObjectWrapper<Serialize> getSerialize(byte serializeCode) {
        ObjectWrapper<Serialize> serializeWrapper = SERIALIZE_CACHE_CODE.get(serializeCode);
        if (serializeWrapper == null){
            return SERIALIZE_CACHE_CODE.get((byte)1);
        }
        return SERIALIZE_CACHE_CODE.get(serializeCode);
    }

    /**
     * 新增一个新的序列化器的包装
     * @param serializeObjectWrapper
     */
    public static void addSerializer(ObjectWrapper<Serialize> serializeObjectWrapper){
        SERIALIZE_CACHE.put(serializeObjectWrapper.getName(),serializeObjectWrapper);
        SERIALIZE_CACHE_CODE.put(serializeObjectWrapper.getCode(),serializeObjectWrapper);
    }

}
